package com.lion.appletrip.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.lion.appletrip.GridViewAllActivity;
import com.lion.appletrip.GridViewShareActivity;
import com.lion.appletrip.ListViewActivity;
import com.lion.appletrip.R;
import com.lion.appletrip.fragment.item.FragmenHeadview_banner;
import com.lion.appletrip.model.BannerData;
import com.lion.appletrip.model.Breakdata;
import com.lion.appletrip.model.Data;
import com.lion.appletrip.model.Element;
import com.lion.appletrip.model.SearchDatum;
import com.lion.appletrip.model.GridView.User;
import com.lion.appletrip.model.ListView.ContentData;
import com.lion.appletrip.utils.ApiClient;
import com.lion.appletrip.utils.CustomerGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.romainpiel.titanic.library.Titanic;
import com.romainpiel.titanic.library.TitanicTextView;
import com.xinbo.utils.GsonUtils;
import com.xinbo.utils.UILUtils;
import com.xinbo.utils.VolleyListener;
import com.xinbo.widget.ViewPagerIndicator;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 *
 */
public class Fragment1 extends Fragment
{
	private PullToRefreshListView mPullRefreshListView;
	private LayoutInflater inflater;
	private ViewPager mPager;
	private boolean needAuto;
	private boolean isDrag;
	private ViewPagerIndicator mIndicator;
	private List<Element> elements = new ArrayList<Element>();
	private List<Element> elements2 = new ArrayList<Element>();
	private List<BannerData> bannerList = new ArrayList<BannerData>();
	private List<com.lion.appletrip.model.GridView.Datum> gridList = new ArrayList<com.lion.appletrip.model.GridView.Datum>();
	private List<ContentData> listViewData = new ArrayList<ContentData>();
	private GridAdapter gridAdapter;
	private GridView mGridView;
	private MyAdapter adapter;
	private ListView actualListView;
	private int size = 5;
	private View lionfg1;
	private View btnMore;
	private View layoutf;
	private boolean isComplete;
	private TitanicTextView ivLoading;
	
	private PopAdapter popAdapter;
	private PopAdapter2 popAdapter2;
	private Titanic titanic;
	private TextView btnSearch;
	public Fragment1()
	{
	}

	@SuppressLint("InflateParams")
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	        Bundle savedInstanceState)
	{
		this.inflater = inflater;
		needAuto = true;
		if (layoutf==null)
        {
			layoutf = inflater.inflate(R.layout.fragment_fragment1, container,
					false);
			View headViewTitle = inflater.inflate(
					R.layout.title_fragment1_headview1, null);
			
			mPullRefreshListView = (PullToRefreshListView) layoutf
					.findViewById(R.id.pull_refresh_list);
			lionfg1 = layoutf.findViewById(R.id.lion_fg1);
			btnSearch = (TextView) layoutf.findViewById(R.id.btn_search);
			ivLoading= (TitanicTextView) layoutf.findViewById(R.id.my_text_view_fg1);
			adapter = new MyAdapter();
			popAdapter = new PopAdapter();
			popAdapter2 = new PopAdapter2();
			titanic = new Titanic();
			titanic.start(ivLoading);
			// 初始化headview布局
			initHeadview(headViewTitle);
			initData();
			// 设置下拉刷新监听事件
			mPullRefreshListView
			.setOnRefreshListener(new OnRefreshListener<ListView>()
					{
				@Override
				public void onRefresh(
						PullToRefreshBase<ListView> refreshView)
				{
					String label = DateUtils.formatDateTime(getContext(),
							System.currentTimeMillis(),
							DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);
					// 更新刷新时间
					refreshView.getLoadingLayoutProxy()
					.setLastUpdatedLabel(label);
					// 刷新内容
					initData();
					onRefreshComplete();
				}
					});
			// 设置上拉加载更多监听事件
			actualListView = mPullRefreshListView.getRefreshableView();
			actualListView.addHeaderView(headViewTitle, null, false);
			actualListView.setAdapter(adapter);
	        
        }
		return layoutf;
	}

	private void initpulltorefresh()
	{
		mPullRefreshListView
		        .setOnLastItemVisibleListener(new OnLastItemVisibleListener()
		        {

			        @Override
			        public void onLastItemVisible()
			        {
				        if (size < listViewData.size()-5)
				        {
					        size += 5;
				        }else {
							size=listViewData.size()-1;
							if (!isComplete)
                            {
								Toast.makeText(getContext(), "全部加载完成",
										Toast.LENGTH_SHORT).show();
	                            isComplete=true;
                            }
						}
				        adapter.notifyDataSetChanged();
			        }
		        });
	}
	
	private void initData()
	{
		ApiClient.homeDateGet(getContext(), new VolleyListener()
		{

			

			@Override
			public void onResponse(String json)
			{
				jsonToText(json);
				Breakdata breakdata = GsonUtils
				        .parseJSON(json, Breakdata.class);
				Data data = breakdata.getData();
				List<SearchDatum> searchData = data.getSearchData();
				if (searchData.size()>0)
                {
					SearchDatum searchDatum = searchData.get(0);
					elements = searchDatum.getElements();
					popAdapter.notifyDataSetChanged();
					if (searchData.size()>1)
                    {
	                    SearchDatum searchDatum2 = searchData.get(1);
	                    elements2 = searchDatum2.getElements();
	                    popAdapter2.notifyDataSetChanged();
                    }
                }
			}

			@Override
			public void onErrorResponse(VolleyError arg0)
			{

			}
		});

	}

	protected void initSearch()
    {
		View view = inflater.inflate(R.layout.fragment_fragment1_popuwindows, null);
		PopupWindow popupWindow = new PopupWindow(view,LayoutParams.MATCH_PARENT, 
				LayoutParams.MATCH_PARENT,true);
		ColorDrawable cd = new ColorDrawable(-0000);
		popupWindow.setBackgroundDrawable(cd);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(view,Gravity.CENTER,0 ,0);
		CustomerGridView mGridView = (CustomerGridView) view.findViewById(R.id.customerGridView1_popuwindows);
		CustomerGridView mGridView2 = (CustomerGridView) view.findViewById(R.id.customerGridView2_popuwindows);
		mGridView.setAdapter(popAdapter);
		mGridView2.setAdapter(popAdapter2);
    }
	class PopAdapter extends BaseAdapter
	{

		@Override
        public int getCount()
        {
	        return elements.size();
        }

		@Override
        public Object getItem(int position)
        {
	        return null;
        }

		@Override
        public long getItemId(int position)
        {
	        return 0;
        }

		@Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
			View layout = inflater.inflate(R.layout.fragment_fragment1_popuwindows_item, null);
			TextView mTextView = (TextView) layout.findViewById(R.id.tv_popuwindows);
			mTextView.setText(elements.get(position).getName());
	        return layout;
        }
		
	}
	class PopAdapter2 extends BaseAdapter
	{

		@Override
        public int getCount()
        {
	        return elements2.size();
        }

		@Override
        public Object getItem(int position)
        {
	        return null;
        }

		@Override
        public long getItemId(int position)
        {
	        return 0;
        }

		@Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
			View layout = inflater.inflate(R.layout.fragment_fragment1_popuwindows_item, null);
			TextView mTextView = (TextView) layout.findViewById(R.id.tv_popuwindows);
			mTextView.setText(elements2.get(position).getName());
	        return layout;
        }
		
	}
	protected void jsonToText(String json)
	{
		listViewData.clear();
		bannerList.clear();
		gridList.clear();
		try
		{
			JSONObject jsonObject = new JSONObject(json);
			JSONObject data = jsonObject.getJSONObject("data");
			JSONArray elements = data.getJSONArray("elements");
			for (int i = 0; i < elements.length(); i++)
			{
				JSONObject element = elements.getJSONObject(i);
				JSONArray mData = element.getJSONArray("data");
				if (i == 0)
				{
					JSONArray list = mData.getJSONArray(0);
					for (int j = 0; j < list.length(); j++)
					{
						JSONObject bannerObject = list.getJSONObject(j);
						String platform = bannerObject.getString("platform");
						String image_url = bannerObject.getString("image_url");
						String html_url = bannerObject.getString("html_url");
						bannerList.add(new BannerData(platform, image_url,
						        html_url));
					}
				} else if (i == 1)
				{

				} else if (i == 2 || i == 3 || i == 4 || i == 5)
				{

					JSONObject gridData = mData.getJSONObject(0);
					String text = gridData.getString("text");
					boolean isLiked = gridData.getBoolean("is_liked");
					String indexCover = gridData.getString("index_cover");
					String coverImageS = gridData.getString("cover_image_s");
					boolean isHidingLocation = gridData
					        .getBoolean("is_hiding_location");
					long spotId = gridData.getLong("spot_id");
					// user 的json解析数据
					JSONObject user = gridData.getJSONObject("user");
					String locationName = user.getString("location_name");
					String name = user.getString("name");
					String avatarS = user.getString("avatar_s");
					User user2 = new User(locationName, name, avatarS);
					// Region的json解析数据
					/*
					 * JSONObject region = gridData.getJSONObject("region");
					 * String primary = region.getString("primary"); String
					 * secondary = region.getString("secondary"); Region region2
					 * = new Region(secondary, secondary);
					 */
					com.lion.appletrip.model.GridView.Datum userdata = new com.lion.appletrip.model.GridView.Datum(
					        text, isLiked, indexCover, coverImageS,
					        isHidingLocation, user2, spotId);
					gridList.add(userdata);
					userdata = null;
					user2 = null;
					// region2=null;
				} else if (i == 6)
				{

				} else if (i >= 7 && i < elements.length())
				{

					JSONObject listData = mData.getJSONObject(0);
					String coverImageDefault = listData
					        .getString("cover_image_default");
					long id = listData.getLong("id");
					int viewCount = listData.getInt("view_count");
					int dayCount = listData.getInt("day_count");
					String popularPlaceStr = listData
					        .getString("popular_place_str");
					String name = listData.getString("name");
					String firstDay = listData.getString("first_day");
					// user的json数据解析
					JSONObject userData = listData.getJSONObject("user");
					String name_ = userData.getString("name");
					String avatarS = userData.getString("avatar_s");
					com.lion.appletrip.model.ListView.User user = new com.lion.appletrip.model.ListView.User(
					        name_, avatarS);
					ContentData contentData = new ContentData(
					        coverImageDefault, id, viewCount, dayCount, user,
					        popularPlaceStr, name, firstDay);
					listViewData.add(contentData);
					contentData = null;
					user = null;
					// startPoint=null;
				}

			}
		
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		initMpager(bannerList);
		gridAdapter.notifyDataSetChanged();
		adapter.notifyDataSetChanged();
		titanic.cancel();
		ivLoading.setVisibility(View.GONE);
		lionfg1.setVisibility(View.VISIBLE);
		mGridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			        int position, long id)
			{
				com.lion.appletrip.model.GridView.Datum datum = gridList
				        .get(position);
				Long spotId = datum.getSpotId();
				Intent intent = new Intent();
				intent.putExtra("spotId", spotId);
				intent.setClass(getContext(), GridViewShareActivity.class);
				startActivity(intent);
			}
		});
		actualListView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			        int position, long id)
			{	
				position-=2;
				ContentData contentData = listViewData.get(position);
				Long urlId = contentData.getId();
				Intent intent = new Intent();
				intent.putExtra("urlId", urlId);
				intent.setClass(getContext(), ListViewActivity.class);
				startActivity(intent);
			}
		});
		btnMore.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(getContext(), GridViewAllActivity.class);
				startActivity(intent);
			}
		});
		btnSearch.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				initSearch();
				
			}
		});
		initpulltorefresh();
	}

	private void initHeadview(View headViewTitle)
	{
		mPager = (ViewPager) headViewTitle.findViewById(R.id.viewPager1);
		mIndicator = (ViewPagerIndicator) headViewTitle
		        .findViewById(R.id.viewPagerIndicator1);
		mGridView = (GridView) headViewTitle.findViewById(R.id.gridView1);
		btnMore = headViewTitle.findViewById(R.id.lion_to_more);
		gridAdapter = new GridAdapter();
		mGridView.setAdapter(gridAdapter);
	}

	private void initMpager(final List<BannerData> bannerData)
	{
		FragmentManager fm = getChildFragmentManager();
		mPager.setAdapter(new FragmentPagerAdapter(fm)
		{
			@Override
			public int getCount()
			{

				return 20000;
			}

			@Override
			public Fragment getItem(int position)
			{
				int index = position % 5;
				return new FragmenHeadview_banner(bannerData, index);
			}
		});
		
		mPager.addOnPageChangeListener(new OnPageChangeListener()
		{
			@Override
			public void onPageSelected(int arg0)
			{
			}

			@Override
			public void onPageScrolled(int position, float percent, int arg2)
			{
				mIndicator.move(percent, position % 5);
			}

			@Override
			public void onPageScrollStateChanged(int state)
			{
				switch (state)
				{
				case ViewPager.SCROLL_STATE_DRAGGING:
					isDrag = true;
					break;
				case ViewPager.SCROLL_STATE_IDLE:
					isDrag = false;
					break;
				case ViewPager.SCROLL_STATE_SETTLING:
					isDrag = false;
					break;
				default:
					break;
				}
			}
		});
		mPager.postDelayed(new Runnable()
		{

			@Override
			public void run()
			{
				if (!isDrag && needAuto)
				{
					int currentItem = mPager.getCurrentItem() + 1;
					mPager.setCurrentItem(currentItem);
				}
				mPager.postDelayed(this, 5000);
			}
		}, 5000);
	}
	@Override
	public void onStop()
	{
		initClear();
	    super.onStop();
	}

	private void initClear()
    {
	    needAuto=false;
		ImageLoader.getInstance().clearMemoryCache();
    }
	@Override
	public void onResume()
	{
		needAuto=true;
	    super.onResume();
	}
	@Override
	public void onDestroyView()
	{	
		initClear();
		super.onDestroyView();
	}
	// GridView内容适配器
	class GridAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{
			return gridList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return null;
		}

		@Override
		public long getItemId(int position)
		{

			return 0;
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View layout = null;
			ViewHolder viewHolder = null;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				layout = inflater.inflate(
				        R.layout.fragment_fragment1_gridview_item, null);
				viewHolder.indexCover = (ImageView) layout
				        .findViewById(R.id.iv_index_cover);
				viewHolder.tvlicationName = (TextView) layout
				        .findViewById(R.id.tv_location_name);
				viewHolder.tvContent = (TextView) layout
				        .findViewById(R.id.tv_content);
				viewHolder.avatar = (ImageView) layout
				        .findViewById(R.id.iv_avatar_s);
				viewHolder.tvNick = (TextView) layout
				        .findViewById(R.id.tv_nickname);
				layout.setTag(viewHolder);
			} else
			{
				layout = convertView;
				viewHolder = (ViewHolder) layout.getTag();
			}
			com.lion.appletrip.model.GridView.Datum datum = gridList
			        .get(position);
			UILUtils.displayImageNoAnim(datum.getIndexCover(),
			        viewHolder.indexCover);
			viewHolder.tvlicationName
			        .setText(datum.getUser().getLocationName());
			viewHolder.tvContent.setText(datum.getText());
			viewHolder.tvNick.setText(datum.getUser().getName());
			UILUtils.displayImageNoAnim(datum.getUser().getAvatarS(),
			        viewHolder.avatar);
			return layout;
		}

	}

	class ViewHolder
	{
		ImageView indexCover;
		TextView tvlicationName;
		TextView tvContent;
		ImageView avatar;
		TextView tvNick;
		ImageView ivCover;
		TextView tvName;
		TextView tvFristDay;
		TextView tvDayCount;
		TextView tvViewCount;
		TextView tvPopularPlaceStr;
		TextView tvUserName;
		ImageView avatarM;
	}

	// listview内容适配器
	class MyAdapter extends BaseAdapter
	{
		@Override
		public int getCount()
		{
			int num = 0;
			if (listViewData.size() > 0)
			{
				num = size;
			}
			return num;
		}

		@Override
		public Object getItem(int position)
		{
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			return 0;
		}

		@SuppressLint("InflateParams")
        @Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View layout = null;
			ViewHolder viewHolder = null;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				layout = inflater.inflate(
				        R.layout.fragment_fragment1_listview_item, null);
				viewHolder.ivCover = (ImageView) layout
				        .findViewById(R.id.cover_image_default);
				viewHolder.tvName = (TextView) layout
				        .findViewById(R.id.tv_name);
				viewHolder.tvFristDay = (TextView) layout
				        .findViewById(R.id.tv_first_day);
				viewHolder.tvDayCount = (TextView) layout
				        .findViewById(R.id.tv_day_count);
				viewHolder.tvViewCount = (TextView) layout
				        .findViewById(R.id.tv_view_count);
				viewHolder.tvPopularPlaceStr = (TextView) layout
				        .findViewById(R.id.tv_popular_place_str);
				viewHolder.avatarM = (ImageView) layout
				        .findViewById(R.id.circleImageView1_avatar_m);
				viewHolder.tvUserName = (TextView) layout
				        .findViewById(R.id.tv_user_name);
				layout.setTag(viewHolder);
			} else
			{
				layout = convertView;
				viewHolder = (ViewHolder) layout.getTag();
			}
			ContentData contentData = listViewData.get(position);
			viewHolder.tvName.setText(contentData.getName());
			viewHolder.tvFristDay.setText(contentData.getFirstDay());
			viewHolder.tvDayCount.setText(contentData.getDayCount() + "天");
			viewHolder.tvViewCount.setText(contentData.getViewCount() + "次浏览");
			viewHolder.tvPopularPlaceStr.setText(contentData
			        .getPopularPlaceStr());
			
				UILUtils.displayImageNoAnim(contentData.getCoverImageDefault(),
						viewHolder.ivCover);
				UILUtils.displayImageNoAnim(contentData.getUser().getAvatarS(),
						viewHolder.avatarM);
            
			viewHolder.tvUserName.setText(contentData.getUser().getName());
			return layout;
		}

	}

	// 刷新方法
	private void onRefreshComplete()
	{	
		
		mPullRefreshListView.postDelayed(new Runnable()
		{

			@Override
			public void run()
			{
				
				mPullRefreshListView.onRefreshComplete();

			}
		}, 2000);
	}

}
